export default class Tab {
    constructor(element, option){
        this.$element = $(element);
        this.$tabNavItems = this.$element.find('a');
        this.$tabContents = $(this.$element.data('target')).children();
        this.options = Object.assign({}, option);
        this.init();
    }

    init(){
        if(this.$tabNavItems.length < 1){
            throw new Error( '没有A标签，获取tab导航条不存在' );
        }
        this.show(this.options.index);
        this.handleToggle();
    }



    show(index){
        if(index === undefined) return;
        this.$tabNavItems.parent().eq(index).addClass('active').siblings().removeClass('active');
        this.$tabContents.eq(index).addClass('active').siblings().removeClass('active');
    }



    handleToggle(){
        this.$tabNavItems.on('click.tab', (e)=>{
            e.stopPropagation();
            e.preventDefault();
            const $element = $(e.target);
            if($element.parent().hasClass('active')){
                return false;
            }
            const options = this.options;
            const index = this.$tabNavItems.index($element);
            if(options.beforeShow){ //promise 对象
                options.beforeShow(e).then( ()=> {
                    this.show(index);
                });
                return false;
            }
            this.show(index);
        })
    }
}

